package com.sengled.cloud.biz.union.mgt.api.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.sengled.cloud.biz.union.mgt.common.SysConstants;
import com.sengled.cloud.biz.union.mgt.common.util.CurrentUserUtil;
import com.sengled.cloud.biz.union.mgt.model.po.User;
import com.sengled.cloud.biz.union.mgt.model.request.LoginRequest;
import com.sengled.cloud.biz.union.mgt.model.request.SaveUserRequest;
import com.sengled.cloud.biz.union.mgt.model.request.SetAccountStatusRequest;
import com.sengled.cloud.biz.union.mgt.model.request.UserListQueryRequest;
import com.sengled.cloud.biz.union.mgt.model.response.PcLoginDataResponse;
import com.sengled.cloud.biz.union.mgt.model.response.ResponseMessage;
import com.sengled.cloud.biz.union.mgt.model.vo.*;
import com.sengled.cloud.biz.union.mgt.service.sys.IRoleManageService;
import com.sengled.cloud.biz.union.mgt.service.sys.IUserService;
import com.sengled.cloud.biz.union.mgt.service.sys.impl.AccountService;

import io.swagger.annotations.*;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.util.List;

/**
 * Created by FMC on 2017/10/27.
 */
@RestController
@RequestMapping("/api/v1")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleManageService roleManageService;
    
    @Autowired
    private AccountService accountService;

    @ApiOperation(value = "获取人员列表", notes = "获取人员列表", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "userCode", value = "职员ID", dataType = "String", paramType = "query", defaultValue = "zs"),
            @ApiImplicitParam(name = "userName", value = "姓名", dataType = "String", paramType = "query", defaultValue = "张三"),
            @ApiImplicitParam(name = "roleId", value = "职位", dataType = "Long", paramType = "query",defaultValue ="1"),
            @ApiImplicitParam(name = "shopId", value = "归属店铺", dataType = "Long", paramType = "query",defaultValue ="1"),
            @ApiImplicitParam(name = "pageNo", value = "当前页码", dataType = "Long", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "显示条数", dataType = "Long", paramType = "query", defaultValue = "30")
    })
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    @RequestMapping(value = "/users/", method = RequestMethod.GET)
    public ResponseMessage<List<UserVo>> getShops(@ApiParam(name = "userCode", required = true) String userCode,
                                                      @ApiParam(name = "userName", required = true) String userName,
                                                      @ApiParam(name = "roleId", required = true) Integer roleId,
                                                      @ApiParam(name = "shopId", required = true) Integer shopId,
                                                      @ApiParam(name = "pageNo") Integer pageNo,
                                                      @ApiParam(name = "pageSize") Integer pageSize,HttpServletRequest request) {
    	UserListQueryRequest query = new UserListQueryRequest();
        query.setPageNo(pageNo);
        query.setPageSize(pageSize);
        query.setUserCode(userCode);
        query.setUserName(userName);
        query.setRoleId(roleId);
        query.setShopId(shopId);
        Long customerId = CurrentUserUtil.getCurrentAccountId(request);
        Long companyId = userService.getCompanyId(customerId);
        query.setCompanyId(companyId);
        query.setUserId(customerId);
        return userService.listUsersByPage(query);
    }

    @ApiOperation(value = "查看人员", notes = "查看人员", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "id", value = "人员id", dataType = "Long", paramType = "path", required = true)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    
    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public ResponseMessage<UserDetailVo> getById(@ApiParam(name = "id", required = true) @PathVariable Long id) {
        return userService.getUserDetailById(id);
    }

    @ApiOperation(value = "新增人员保存", notes = "新增人员保存接口", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    @RequestMapping(value = "/user/", method = RequestMethod.POST)
    public ResponseMessage<User> createMessage(@RequestBody SaveUserRequest saveUserRequest,HttpServletRequest request) {
    	saveUserRequest.setId(null);
    	Long customerId = CurrentUserUtil.getCurrentAccountId(request);
        return userService.saveOrUpdate(saveUserRequest,customerId);
    }

    @ApiOperation(value = "编辑人员保存", notes = "编辑人员保存", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    @RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
    public ResponseMessage<User> putUser(@ApiParam(value = "人员ID", required = true) @PathVariable Long id, @RequestBody SaveUserRequest saveUserRequest,HttpServletRequest request) {
    	saveUserRequest.setId(id);
    	Long customerId = CurrentUserUtil.getCurrentAccountId(request);
        return userService.saveOrUpdate(saveUserRequest,customerId);
    }


    @ApiOperation(value = "删除人员", notes = "删除人员", produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误"),
            @ApiResponse(code = 20003, message = "执行失败")
    })
    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public ResponseMessage deleteUser(@ApiParam(value = "职员ID", required = true) @PathVariable Long id) {
        return userService.delete(id);
    }

    @ApiOperation(value = "获取职位下拉列表数据", notes = "获取职位下拉列表数据", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/user/roles/list/", method = RequestMethod.GET)
    public ResponseMessage<List<SelectBoxDataVo>> getRoleList(HttpServletRequest request) {
    	Long customerId = CurrentUserUtil.getCurrentAccountId(request);
        return userService.getRoleSelectData(customerId);
    }
    
    @ApiOperation(value = "获取店铺下拉列表数据", notes = "获取店铺下拉列表数据", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/user/shops/list/", method = RequestMethod.GET)
    public ResponseMessage<List<SelectBoxDataVo>> getShopList(HttpServletRequest request) {
    	Long customerId = CurrentUserUtil.getCurrentAccountId(request);
    	
        return userService.getShopSelectData(customerId);
    }

    
    @RequestMapping(value = "/user/checkLogin", method = RequestMethod.GET)
    public String getEditPageById(HttpServletRequest request) {
        ResponseMessage<PcLoginDataResponse> rm = new ResponseMessage<PcLoginDataResponse>();
        String username = CurrentUserUtil.getCurrentAccountUser(request);
        if(StringUtils.isNotEmpty(username)){
            rm = roleManageService.getPcLoginData(username,"PC");
        }else{
            rm.buildUserUnLoginMessage();
        }
        return JSON.toJSONString(rm, SerializerFeature.DisableCircularReferenceDetect);
    }


    @ApiOperation(value = "编辑用户查询", notes = "编辑用户查询", produces = MediaType.APPLICATION_JSON_VALUE)
    @RequestMapping(value = "/user/edit/{id}", method = RequestMethod.GET)
    public ResponseMessage<UserEditDetailVo> checkLogin(@ApiParam(name = "id", required = true) @PathVariable Long id) {
        return userService.getUserEditDetailById(id);
    }
    
//    @ApiOperation(value = "上传消息接收客户名单upload请求", notes = "上传消息接收客户名单", produces = MediaType.APPLICATION_JSON_VALUE)
//    @ApiResponses(value = {
//            @ApiResponse(code = 200, message = "正常"),
//            @ApiResponse(code = 10001, message = "系统错误"),
//            @ApiResponse(code = 20002, message = "参数错误")
//    })
//    @RequestMapping(value = "/message/uploadExcel", method = RequestMethod.POST)
//    public String uploadExcel(@RequestParam("sourceFile") MultipartFile sourceFile) throws IOException {
//        //判断文件是否为空
//        if (sourceFile == null) {
//            return null;
//        }
//        //获取文件名
//        String name = sourceFile.getOriginalFilename();
//        //进一步判断文件是否为空（即判断其大小是否为0或其名称是否为null）
//        long size = sourceFile.getSize();
//        if (name == null || ("").equals(name) && size == 0) {
//            return null;
//        }
//
//        //批量导入。参数：文件名，文件。
//        List<MessageView> receivers = null;
//        JSONObject jsonObject = new JSONObject();
//        if (receivers != null && receivers.size() > 0) {
//            jsonObject.put("flag", 0);
//            jsonObject.put("success", "批量导入EXCEL成功");
//            JSONArray jsonArray = JSONArray.fromObject(receivers);
//            jsonObject.put("receivers", jsonArray);
//        } else {
//            jsonObject.put("flag", 1);
//            jsonObject.put("success", "批量导入EXCEL失败");
//        }
//        return jsonObject.toString();
//    }


    @ApiOperation(value = "测试登录请求", notes = "登录接口")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "正常"),
            @ApiResponse(code = 10001, message = "系统错误"),
            @ApiResponse(code = 20002, message = "参数错误")
    })
    @RequestMapping(value = "/login/data", method = {RequestMethod.POST})
    @ResponseBody
    public String padOrPcLogin(HttpServletRequest request) {
        ResponseMessage<PcLoginDataResponse> rm = new ResponseMessage<PcLoginDataResponse>();
        ResponseMessage<LoginDataResponse> rmApp = new ResponseMessage<LoginDataResponse>();
        //多角色用户，去掉重复模块，去掉重复权限

        String channel = null;
        String uuid = null;
        String osType = null;
        String username = null;
        String password = null;
        LoginRequest loginRequest = new LoginRequest();

        if(request.getAttribute("biz-union-user-channel")!=null){
            channel = (String)request.getAttribute("biz-union-user-channel");
            loginRequest.setChannel(channel);
        }
        if(request.getAttribute("biz-union-user-uuid")!=null){
            uuid = (String)request.getAttribute("biz-union-user-uuid");
            loginRequest.setUuid(uuid);
        }
        if(request.getAttribute("biz-union-user-osType")!=null){
            osType = (String)request.getAttribute("biz-union-user-osType");
            loginRequest.setOs_type(osType);
        }
        if(request.getAttribute("biz-union-user-username")!=null){
            username = (String)request.getAttribute("biz-union-user-username");
            loginRequest.setUser(username);
        }
        if(request.getAttribute("biz-union-user-password")!=null){
            password = (String)request.getAttribute("biz-union-user-password");
            loginRequest.setPwd(password);
        }
        try{
            setAccountStatus(null,username,1);
        }catch(Exception e){
        	 rm.buildSystemErrorMessage();
        	 return JSON.toJSONString(rm);
        }
        if(SysConstants.CHANNEL_PC.equals(loginRequest.getChannel())){
            rm = roleManageService.getPcLoginData(loginRequest.getUser(),loginRequest.getChannel());
            return JSON.toJSONString(rm, SerializerFeature.DisableCircularReferenceDetect);
        }else{
            //APP不关心模块层级关系
            rmApp = roleManageService.getAppLoginData(loginRequest.getUser(),loginRequest.getChannel());
            return JSON.toJSONString(rmApp,SerializerFeature.DisableCircularReferenceDetect);
        }
    }
    
    public void setAccountStatus(Long id,String accountName,Integer status){
    	SetAccountStatusRequest setAccountStatusRequest = new SetAccountStatusRequest();
    	setAccountStatusRequest.setAccountName(accountName);
    	setAccountStatusRequest.setAccountStatus(status);
    	accountService.setAccountStatusByName(setAccountStatusRequest);
    	
    }
}
